package com.kaifamiao.jdbc.meta;

import java.sql.*;

/**
 * 1、CallableStatement接口 是 PreparedStatement接口 的子接口
 * 2、PreparedStatement接口 是 Statement接口 的子接口
 * 3、获取 被调用的存储过程 的参数元数据
 * 4、获取 传出参数的值
 */
public class GetParameterMetaData {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        String driverClassName = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/kaifamiao?serverTimezone=Asia/Chongqing";
        String username = "kfm";
        String password = "kfm";

        // 加载并注册驱动
        Class.forName(driverClassName);
        // 建立连接
        Connection conn = DriverManager.getConnection(url, username, password);

        CallableStatement cs = conn.prepareCall( "CALL find_name_sal( ?, ? )" );

        // 获得参数元数据
        ParameterMetaData meta = cs.getParameterMetaData();
        final int count = meta.getParameterCount();
        System.out.println( count );
        for (int i = 1; i <= count; i++) {
            int mode = meta.getParameterMode( i );
            int sqlType = meta.getParameterType( i );
            String sqlTypeName = meta.getParameterTypeName( i );
            String className = meta.getParameterClassName( i );
            System.out.println( sqlType + ", " + sqlTypeName + ", " + className + ", " + mode );
        }

        // 显示注册"传出(OUT)参数"
        cs.registerOutParameter( 1, meta.getParameterType( 1 ) );
        cs.registerOutParameter( 2 , meta.getParameterType( 2 ) );

        // 设置传入参数的值
        cs.setObject( 2, 9527, meta.getParameterType( 2 ) );
        int num = cs.executeUpdate();
        System.out.println( num );

        // 获取传出参数的值
        String name = cs.getString( 1 ); // Object value = cs.getObject( 1 );
        Double salary = cs.getDouble( 2 );
        System.out.println( name + ", " + salary );

        // 释放资源
        cs.close();
        conn.close();

    }

}
